let conf = require('../../app.config').app
let api = require('../../common/js/api')
const app = getApp();
const { tagOperation } = require('../../common/js/utils.js')
const cvs = require('./draw')

Component({

  properties: {
    type: { type: String, value: '', observer(e) {
      console.log('e', e)
        let sceneVal='';
        if(e=='送你1张优惠券'){
          sceneVal='ST=1&OpID='+this.data.userinfo.customerId          
        }else if(e=='送你1份试用礼'){
          sceneVal='ST=2&OrId='+this.data.friendOntrialOrderId
        } 
        console.log('sceneVal',sceneVal)
        if (sceneVal) {
            api.interface.qrcode({
                scene: sceneVal,
                page: 'pages/home/home'
            }).then(r => {
                console.log('ajax--interface.qrcode:', r.data);
                if (r.data.code == 200) {
                    this.setData({qrcode:r.data.data})                       
                } else {
                    wx.showToast({
                        title: r.data.message,
                        icon: 'none'
                    })
                }
            })
        }
      
    } },
    // 是否是手动关闭
    isManualClose: { type: Boolean, value: false },
    // 用户信息
    userinfo: { type: Object, value: {}, observer(e) {
      if (e.nickName) {
        this.setData({ 'nickNameSave': this.handleNameLen(e.nickName, 8) })
      }
    } },
    // 是否是新用户
    isNewUser: { type: Boolean, value: false },
    // 新用户是否已领取
    isNewUserGet: { type: Boolean, value: false },
    // 单张优惠券
    coupon: { type: Object, value: {} },
    // 多张优惠券
    coupons: { type: Array, value: [] },
    //试用礼的friendOntrialOrderId
    friendOntrialOrderId:{type:String,value:''}
  },

  data: {
    alert: '',
    // 海报生成
    cvsBox: { width: 600, height: 818 },
    nickNameSave: '',
    qrcode:'',

  },

  attached() {
    // 初始化
    this.setData({
      alert: this.selectComponent("#alert"),
    });

  },

  methods: {

    // 关闭弹窗
    close() {
      if (this.data.isManualClose) {
        this.triggerEvent('onAlertClose')
      } else {
        let pages = getCurrentPages()
        let prevPage = pages[pages.length - 1]//当前页面录路由
        prevPage.setData({
          alertType: ''
        })
      }
    },

    // 前往答题
    tapGoAnswer() {
      app.tongji.se({ key: 'qwdtan', label: '前往答题按钮' })
      this.close()
      wx.navigateTo({ url: '../qna/index' })
    },

    // 下载图片
    downloadFile(_path) {
      return new Promise((resolve, reject) => {
        wx.downloadFile({
          url: _path,
          success(res) { resolve(res.tempFilePath) },
          fail(err) {
            console.log('err', err)
            reject(err)
          },
        })
      })
    },

    // Promise方式 封装
    isAuthorize() {
      return new Promise((resolve, reject) => {
        wx.authorize({ scope: 'scope.writePhotosAlbum' }).then(() => {
          resolve()
        }).catch(() => {
          wx.getSetting().then(r => {
            if (!r.authSetting['scope.writePhotosAlbum']) {
              wx.showModal({
                title: '是否授权保存到相册',
                content: '请确认授权，否则无法保存到相册',
                success: tip => {
                  if (tip.confirm) {
                    wx.openSetting()
                  }
                }
              })
            }
          })
        })
      })
    },

    handleNameLen(playerName, len) {
      let new_playerName = ""
      if (playerName.length > len) {
          new_playerName = playerName.substring(0, len);
          new_playerName += "..."
      } else {
          new_playerName = playerName;
      }
      return new_playerName;
    },

    // 保存分享图
    tapPosterSave(e) {
      this.isAuthorize().then(async () => {
        let { cdn } = this.data
        let { type } = e.currentTarget.dataset
        let img = ''
        let saveSrc = ''
        if (type == '优惠券') {
          app.tongji.se({ key: 'hyyqhbbcfxt', label: '好友邀请海报保存分享图' })
          // img = await this.downloadFile(`${cdn}taskCenter/poster-coupon.png`)
          saveSrc = `${cdn}taskCenter/poster-coupon-new.png`
        } else if (type == '试用礼') {
          app.tongji.se({ key: 'hysyfldhhbbc', label: '好友试用福利海报保存' })
          // img = await this.downloadFile(`${cdn}taskCenter/share-worth.png`)
          saveSrc = `${cdn}taskCenter/share-worth-new.png`
        }
        let qrcode = this.data.qrcode||`${cdn}taskCenter/qr.png`
        this.setData({qrcode}); //合成完了才能显示。
        var settings = {
          basedata: { width: 600, height: 818 },
          data: [
            { type: "image", src: saveSrc, width: 600, height: 818, x: 0, y: 0 },
            { type: "Rectimg", src: qrcode, width: 136, height: 136, x: 236, y: 660 },
            {
              type: "text", val: this.data.nickNameSave, color: '#000050',
              font: { size: 36, family: '', weight: '' },
              x: 0, y: 210, algin: 'center'
            }
          ]
        }

        cvs.draw('#icvs', this, settings).then(res => {
          wx.canvasToTempFilePath({
            canvas: cvs.canvas,
            x: 0, y: 0,
            width: settings.basedata.width,
            height: settings.basedata.height,
            destWidth: settings.basedata.width,
            destHeight: settings.basedata.height,
            success: function (res) {
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function () {
                  wx.showToast({ title: "保存图片成功！", duration: 2000 })
                }
              })
            },
          }, this)
        })
      })

    },

    // 立即分享
    tapPosterShare(e) {
      console.log('立即分享')
      let { type } = e.currentTarget.dataset
      if (type == '优惠券') {
        app.tongji.se({ key: 'hyyqhbljfx', label: '好友邀请海报立即分享' })
      } else if (type == '试用礼') {
        app.tongji.se({ key: 'hysyfldhhbfx', label: '好友试用福利海报分享' })
      }
      this.close()
    },

    // 送你1份试用礼领取和使用
    tapGetCoupon(e) {
      console.log('送你1张优惠券领取和使用')
      let { isNewUser, isNewUserGet, coupon } = this.data
      if (!isNewUser) { // 老用户
        app.tongji.se({ key: 'hysyfldhqhqan', label: '好友试用福利兑换券领取按钮' })
        this.close()
        this.data.alert.show({
          content: '您不是新用户无法领取',
        })
      } else if (isNewUser && !isNewUserGet) { // 新用户 点击立即领取
        app.tongji.se({ key: 'hysyfldhqhqan', label: '好友试用福利兑换券领取按钮' })
        wx.navigateTo({
          url: '../authorization/authorization?act=' + 4,
        })
      } else if (isNewUser && isNewUserGet) { // 新用户 点击立即试用
        app.tongji.se({ key: 'hysyfldhqljsy', label: '好友试用福利兑换券立即使用' })
        wx.navigateToMiniProgram({
          appId: 'wxb82568e4dfcf56ac',
          path: '/packages/home/dashboard/index',
          complete: () => {
            this.close()
          }
        })
      }
    },

    // 去优惠券
    tapGoCoupon() {
      app.tongji.se({ key: 'xksdfltzdhcg', label: '新客首单福利套组兑换成功' })
      this.close()
      wx.navigateTo({ url: '../coupon/coupon' })
    },

    // 前往积分商城
    tapGoStore() {
      this.close()
      wx.navigateTo({ url: '../store/store' })
    },

    // 优惠券领取成功-立即使用
    tapUseCoupon1() {
      app.tongji.se({ key: 'xksdflrwwctcyhqljsy', label: '新客首单福利任务完成弹窗优惠券立即使用' })
      let { coupon } = this.data
      wx.navigateToMiniProgram({
        appId: coupon.appid,
        path: coupon.path,
        complete: () => {
          this.close()
        }
      })
    },

    // 送你1张优惠券领取和使用
    tapUseCoupon2() {
      console.log('送你1张优惠券领取和使用')
      let { isNewUser, isNewUserGet, coupon } = this.data
      if (!isNewUser) { // 老用户
        app.tongji.se({ key: 'hyyqyhqljlq', label: '好友邀请优惠券立即领取' })
        this.close()
        this.data.alert.show({
          content: '您不是新用户无法领取',
        })
      } else if (isNewUser && !isNewUserGet) { // 新用户 点击立即领取
        app.tongji.se({ key: 'hyyqyhqljlq', label: '好友邀请优惠券立即领取' })
        wx.navigateTo({
          url: '../authorization/authorization?act=' + 3,
        })
      } else if (isNewUser && isNewUserGet) { // 新用户 点击立即试用
        app.tongji.se({ key: 'hyyqyhqljsy', label: '好友邀请优惠券立即使用' })
        wx.navigateToMiniProgram({
          appId: coupon.appid,
          path: coupon.path,
          complete: () => {
            this.close()
          }
        })
      }
    },

    // 恭喜获得新客优惠券-立即使用
    tapUseCoupon3() {
      let { coupon } = this.data
      wx.navigateToMiniProgram({
        appId: 'wxb82568e4dfcf56ac',
        path: '/packages/home/dashboard/index',
        complete: () => {
          this.close()
          wx.removeStorageSync('newUserAuthData')
        }
      })
    },

    // 使用活力值兑换券
    tapVitUseCoupon() {
      console.log('使用活力值兑换券')
      this.close()
    },

    // 前往首页
    onClickOverlay() {
      let pages = getCurrentPages()
      let prevPage = pages[pages.length - 1]//当前页面录路由
      // if (prevPage.route == 'pages/home/home') {
      //   this.close()
      // } else {
      wx.reLaunch({ url: '../home/home' })
      // }
    },

  },

})